# -*- coding: utf-8 -*-
"""
@time：  2021/06/19  16:28
@Auto：Mr. xingye  993843278
@Company 星野训练营 99384378@qq.com
@Function: 程序主入口

"""

from common.Excel import get_writer
from common.Excel import get_reader
from common.Logger import logger, path
from common.mail import Mail
from keywords.interkeys import Inter
import traceback
import datetime


def runcases(line: list, obj, row):
    if len(line[0]) > 0 or len(line[1]) > 0:
        logger.warning("分组信息不执行")
    else:
        # 反射
        try:
            func = getattr(obj, line[3])
        except Exception as e:
            logger.error('关键字%s不存在' % line[3])
            logger.exception(e)
            writer.write(row, 7, 'FAIL', color=2)
            writer.write(row, 8, '关键字%s不存在' % line[3], color=2)
            return

        params = line[4:]
        params = params[:params.index('')]
        try:
            params = params[:params.index(' ')]
        except:
            pass

        try:
            if params:
                res = func(*params)
            else:
                res = func()

            if type(res) == tuple:
                if res[0] == 0:
                    writer.write(row, 7, 'PASS', color=3)
                    writer.write(row, 8, str(res[1]), color=3)
                else:
                    writer.write(row, 7, 'FAIL', color=2)
                    writer.write(row, 8, str(res[1]), color=2)

        except Exception as e:
            logger.error("用例执行错误")
            logger.error(e)
            writer.write(row, 7, 'FAIL', color=2)
            writer.write(row, 8, str(traceback.format_exc()), color=2)


casename = '接口测试用例.xlsx'
reader = get_reader(path + '/lib/' + casename)
writer = get_writer(path + '/lib/' + casename, path + '/lib/result' + casename)
sheetname = reader.get_sheets()
writer.set_sheet(sheetname[0])

lines = reader.readline()
if lines[1][1] == 'Inter':
    obj = Inter()

starttime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
writer.write(1, 3, starttime)
for sheet in sheetname:
    # 设置当前读取的sheet页面
    reader.set_sheet(sheet)
    writer.set_sheet(sheet)
    lines = reader.readline()
    for i in range(1, len(lines)):
        runcases(lines[i], obj, i)
        logger.info(lines[i])

writer.set_sheet(sheetname[0])
endtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
writer.write(1, 4, endtime)
writer.save_close()

mail = Mail()
text = mail.get_summary(path + '/lib/result' + casename)  ###
trs = mail.get_details(path + '/lib/result' + casename)  ###
text = text.replace('mailbody', trs)
mail.send(text)
